import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:rembercount/controller/authLoginController.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:file_selector/file_selector.dart';
import 'dart:typed_data';

class ImportService {
  final CountController countController = Get.find<CountController>();
  final Authlogincontroller authController = Get.find<Authlogincontroller>();
  final ImagePicker _picker = ImagePicker();

  /// 导入CSV文件
  Future<Map<String, dynamic>> importCSV() async {
    try {
      // 根据平台选择不同的文件选择方式
      String? filePath;
      
      if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
        // 桌面端使用手动输入路径
        filePath = await _showFileSelectionDialog();
      } else {
        // 移动端使用文件选择器
        filePath = await _pickFileFromMobile();
      }
      
      if (filePath == null || filePath.isEmpty) {
        return {'success': false, 'message': '未选择文件'};
      }

      File file = File(filePath);
      
      // 检查文件扩展名
      if (!file.path.toLowerCase().endsWith('.csv')) {
        return {'success': false, 'message': '请选择CSV格式的文件'};
      }

      // 检查文件是否存在
      if (!await file.exists()) {
        return {'success': false, 'message': '选择的文件不存在'};
      }

      String content = await file.readAsString(encoding: utf8);

      // 解析CSV内容
      List<Map<String, dynamic>> records = _parseCSV(content);
      
      if (records.isEmpty) {
        return {'success': false, 'message': 'CSV文件格式错误或为空'};
      }

      // 显示预览对话框
      bool shouldImport = await _showPreviewDialog(records);
      
      if (!shouldImport) {
        return {'success': false, 'message': '用户取消导入'};
      }

      // 批量导入记录
      int successCount = 0;
      int failCount = 0;
      List<String> errors = [];

      for (int i = 0; i < records.length; i++) {
        try {
          var record = records[i];
          var res = await _saveRecord(record);
          
          if (res['success']) {
            successCount++;
          } else {
            failCount++;
            errors.add('第${i + 1}行: ${res['message']}');
          }
        } catch (e) {
          failCount++;
          errors.add('第${i + 1}行: $e');
        }
      }

      return {
        'success': true,
        'successCount': successCount,
        'failCount': failCount,
        'errors': errors,
        'message': '导入完成，成功$successCount条，失败$failCount条'
      };

    } catch (e) {
      return {'success': false, 'message': '导入失败: $e'};
    }
  }

  /// 移动端文件选择
  Future<String?> _pickFileFromMobile() async {
    try {
      // 显示选择方式对话框
      String? choice = await _showMobileFileChoiceDialog();
      
      if (choice == null) return null;
      
      if (choice == 'folder') {
        // 从文件夹选择CSV文件
        return await _pickFileFromFolder();
      } else if (choice == 'gallery') {
        // 从相册选择（用户可能将CSV文件保存为图片）
        return await _pickImageFile();
      } else if (choice == 'camera') {
        // 拍照（用户可能拍摄CSV文件）
        return await _pickCameraFile();
      } else if (choice == 'manual') {
        // 手动输入（备用方案）
        return await _showFileSelectionDialog();
      }
      
      return null;
      
    } catch (e) {
      print('移动端文件选择错误: $e');
      // 如果移动端选择失败，回退到手动输入
      return await _showFileSelectionDialog();
    }
  }

  /// 从文件夹选择CSV文件
  Future<String?> _pickFileFromFolder() async {
    try {
      // 创建文件类型过滤器
      const typeGroup = XTypeGroup(
        label: 'CSV文件',
        // extensions: ['csv'],
        // mimeTypes: ['text/csv'],
      );

      // 打开文件选择器
      final XFile? file = await openFile(
        acceptedTypeGroups: [typeGroup],
      );
      
      if (file != null) {
        return file.path;
      }
      
      return null;
    } catch (e) {
      print('文件夹选择错误: $e');
      return null;
    }
  }

  /// 从相册选择图片文件
  Future<String?> _pickImageFile() async {
    try {
      XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
      );
      
      if (pickedFile != null) {
        // 将选择的文件复制到应用目录
        final appDir = await getApplicationDocumentsDirectory();
        final fileName = 'import_${DateTime.now().millisecondsSinceEpoch}.csv';
        final targetPath = '${appDir.path}/$fileName';
        
        // 复制文件
        await File(pickedFile.path).copy(targetPath);
        return targetPath;
      }
      
      return null;
    } catch (e) {
      print('相册选择错误: $e');
      return null;
    }
  }

  /// 拍照选择文件
  Future<String?> _pickCameraFile() async {
    try {
      XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1080,
      );
      
      if (pickedFile != null) {
        // 将选择的文件复制到应用目录
        final appDir = await getApplicationDocumentsDirectory();
        final fileName = 'import_${DateTime.now().millisecondsSinceEpoch}.csv';
        final targetPath = '${appDir.path}/$fileName';
        
        // 复制文件
        await File(pickedFile.path).copy(targetPath);
        return targetPath;
      }
      
      return null;
    } catch (e) {
      print('拍照选择错误: $e');
      return null;
    }
  }

  /// 显示移动端文件选择对话框
  Future<String?> _showMobileFileChoiceDialog() async {
    return await Get.dialog<String>(
      AlertDialog(
        title: const Text('选择CSV文件'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '请选择获取CSV文件的方式：\n\n'
              '1. 从文件夹 - 从文件管理器选择CSV文件\n'
              '2. 从相册 - 如果CSV文件已保存到相册\n'
              '3. 拍照 - 拍摄CSV文件内容\n'
              '4. 手动输入路径 - 直接输入文件路径',
              style: TextStyle(fontSize: 14),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: 'folder'),
            child: const Text('从文件夹'),
          ),
          TextButton(
            onPressed: () => Get.back(result: 'gallery'),
            child: const Text('从相册'),
          ),
          TextButton(
            onPressed: () => Get.back(result: 'camera'),
            child: const Text('拍照'),
          ),
          TextButton(
            onPressed: () => Get.back(result: 'manual'),
            child: const Text('手动输入'),
          ),
        ],
      ),
    );
  }

  /// 显示文件选择对话框（桌面端）
  Future<String?> _showFileSelectionDialog() async {
    final TextEditingController pathController = TextEditingController();
    
    return await Get.dialog<String>(
      AlertDialog(
        title: const Text('选择CSV文件'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '请输入CSV文件的完整路径，或者将文件拖拽到桌面后输入路径',
              style: TextStyle(fontSize: 14),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: pathController,
              decoration: const InputDecoration(
                labelText: '文件路径',
                hintText: '例如: /Users/username/Desktop/data.csv',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '提示：\n1. 将CSV文件放在桌面或文档文件夹\n2. 右键文件选择"显示简介"查看路径\n3. 复制完整路径粘贴到上方',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              String path = pathController.text.trim();
              if (path.isNotEmpty) {
                Get.back(result: path);
              } else {
                Get.snackbar('提示', '请输入文件路径');
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 解析CSV内容
  List<Map<String, dynamic>> _parseCSV(String content) {
    List<Map<String, dynamic>> records = [];
    
    try {
      List<String> lines = content.split('\n');
      if (lines.length < 2) return records;

      // 解析表头
      List<String> headers = _parseCSVLine(lines[0]);
      
      // 解析数据行
      for (int i = 1; i < lines.length; i++) {
        String line = lines[i].trim();
        if (line.isEmpty) continue;

        List<String> values = _parseCSVLine(line);
        if (values.length != headers.length) continue;

        Map<String, dynamic> record = {};
        for (int j = 0; j < headers.length; j++) {
          record[headers[j]] = values[j];
        }

        // 转换为应用数据格式
        Map<String, dynamic> convertedRecord = _convertToAppFormat(record);
        if (convertedRecord.isNotEmpty) {
          records.add(convertedRecord);
        }
      }
    } catch (e) {
      print('CSV解析错误: $e');
    }

    return records;
  }

  /// 解析CSV行
  List<String> _parseCSVLine(String line) {
    List<String> result = [];
    String current = '';
    bool inQuotes = false;
    
    for (int i = 0; i < line.length; i++) {
      String c = line[i];
      
      if (c == '"') {
        inQuotes = !inQuotes;
      } else if (c == ',' && !inQuotes) {
        result.add(current.trim());
        current = '';
      } else {
        current += c;
      }
    }
    
    result.add(current.trim());
    return result;
  }

  /// 转换为应用数据格式
  Map<String, dynamic> _convertToAppFormat(Map<String, dynamic> csvRecord) {
    try {
      // 获取必要字段
      String type = csvRecord['收支类型'] ?? '';
      String amount = csvRecord['金额'] ?? '0';
      String category = csvRecord['分类'] ?? '';
      String subCategory = csvRecord['子分类'] ?? '';
      String date = csvRecord['记账日期'] ?? '';
      String note = csvRecord['备注信息'] ?? '';

      // 验证必要字段
      if (type.isEmpty || amount.isEmpty || category.isEmpty || date.isEmpty) {
        return {};
      }

      // 处理金额
      double amountValue = double.tryParse(amount) ?? 0;
      if (amountValue <= 0) return {};

      // 处理日期格式
      DateTime? recordDate = _parseDate(date);
      if (recordDate == null) return {};

      // 处理分类
      String finalCategory = subCategory.isNotEmpty ? '$category-$subCategory' : category;

      // 构建记录
      return {
        'category': finalCategory,
        'amount': amountValue.toString(),
        'date': recordDate.toIso8601String(),
        'countType': type == '支出' ? 'zhi' : 'shou',
        'note': note,
        'creater': authController.emailController.text,
      };
    } catch (e) {
      print('数据转换错误: $e');
      return {};
    }
  }

  /// 解析日期
  DateTime? _parseDate(String dateStr) {
    try {
      // 尝试多种日期格式
      List<String> formats = [
        'yyyy-M-d H:m',
        'yyyy-M-d H:m:s',
        'yyyy-MM-dd HH:mm',
        'yyyy-MM-dd HH:mm:ss',
        'yyyy/MM/dd HH:mm',
        'yyyy/MM/dd HH:mm:ss',
      ];

      for (String format in formats) {
        try {
          return DateFormat(format).parse(dateStr);
        } catch (e) {
          continue;
        }
      }

      // 如果都失败，尝试标准格式
      return DateTime.tryParse(dateStr);
    } catch (e) {
      print('日期解析错误: $e');
      return null;
    }
  }

  /// 保存单条记录
  Future<Map<String, dynamic>> _saveRecord(Map<String, dynamic> record) async {
    try {
      // 设置控制器数据
      countController.categoryController.text = record['category'];
      countController.amountController.text = record['amount'];
      countController.dateController.text = record['date'];
      countController.countType.value = record['countType'];
      countController.noteController.text = record['note'] ?? '';

      // 保存记录
      var res = await countController.saveCount();
      
      if (res['code'] == 200) {
        return {'success': true, 'message': '保存成功'};
      } else {
        return {'success': false, 'message': res['msg'] ?? '保存失败'};
      }
    } catch (e) {
      return {'success': false, 'message': '保存失败: $e'};
    }
  }

  /// 显示预览对话框
  Future<bool> _showPreviewDialog(List<Map<String, dynamic>> records) async {
    return await Get.dialog<bool>(
      AlertDialog(
        title: const Text('导入预览'),
        content: SizedBox(
          width: double.maxFinite,
          height: 400,
          child: Column(
            children: [
              Text('共发现 ${records.length} 条记录'),
              const SizedBox(height: 16),
              Expanded(
                child: ListView.builder(
                  itemCount:  records.length,
                  itemBuilder: (context, index) {
                    var record = records[index];
                    return ListTile(
                      title: Text('${record['category']} - ¥${record['amount']}'),
                      subtitle: Text('${record['countType'] == 'zhi' ? '支出' : '收入'} - ${record['date']}'),
                      trailing: Text(record['note'] ?? ''),
                    );
                  },
                ),
              ),
              if (records.length > 10)
                const Text('... 还有更多记录', style: TextStyle(color: Colors.grey)),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            child: const Text('确认导入'),
          ),
        ],
      ),
    ) ?? false;
  }
} 